package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameBuddy.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.GameConstant;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.Model;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.SensitivewordEngine;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class BuddyHandler {
	// CMD_GAME_BUDDY_LIST = 71301;// 获取好友列表
	public static Object CMD_GAME_BUDDY_LIST(RequestParam clientParam) throws Exception {
		CSGameBuddyListRequest request = CSGameBuddyListRequest.parseFrom(clientParam.getData());
		CSGameBuddyListResponse.Builder response = CSGameBuddyListResponse.newBuilder();
		long userId = clientParam.getUserId();
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		List<UserBuddy> list = BuddyManager.getUserBuddyList(userId);
		for (UserBuddy userBuddy : list) {
			ProtoDataUtils.updatePBUserData(pbUserData, userBuddy, true);
		}
		UserBuddyApplyInfo userBuddyApplyInfo = BuddyManager.getUserBuddyApplyInfo(userId);
		ProtoDataUtils.updatePBUserData(pbUserData, userBuddyApplyInfo, true);
		return response;
	}


	// CMD_GAME_BUDDY_DEL = 71302;// 删除好友
	public static Object CMD_GAME_BUDDY_DEL(RequestParam clientParam) throws Exception {
		CSGameBuddyDelRequest request = CSGameBuddyDelRequest.parseFrom(clientParam.getData());
		CSGameBuddyDelResponse.Builder response = CSGameBuddyDelResponse.newBuilder();
		long userId = clientParam.getUserId();
		long buddyId = request.getBuddyId();
		UserBuddy userBuddy = BuddyManager.getUserBuddy(userId,buddyId);
		if (userBuddy == null) {
			return ErrorWord.NOT_DATA;
		}
		userBuddy.delete();

		UserBuddy buddyUserBuddy = BuddyManager.getUserBuddy(buddyId,userId);
		if (buddyUserBuddy == null) {
			return ErrorWord.NOT_DATA;
		}
		buddyUserBuddy.delete();
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		ProtoDataUtils.deletePBUserData(pbUserData, userBuddy);
		return response;
	}

	// CMD_GAME_BUDDY_BLACK = 71303;// 拉黑好友
	public static Object CMD_GAME_BUDDY_BLACK(RequestParam clientParam) throws Exception {
		CSGameBuddyBlackRequest request = CSGameBuddyBlackRequest.parseFrom(clientParam.getData());
		CSGameBuddyBlackResponse.Builder response = CSGameBuddyBlackResponse.newBuilder();
		long userId = clientParam.getUserId();
		long buddyId = request.getBuddyId();
		// 不能拉黑自己
		if (buddyId == userId) {
			return ErrorWord.MYSELF;
		}

		UserBuddyBlack userBuddyBlack = BuddyManager.getUserBuddyBlack(userId, buddyId);
		if (userBuddyBlack != null) {
			return ErrorWord.REPEATED_OPERATION;
		}
		// 添加到黑名单
		userBuddyBlack = new UserBuddyBlack(userId, buddyId);
		userBuddyBlack.doCreate();

		// 如果是好友则删除好友
		UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, buddyId);
			if (userBuddy != null) {
			userBuddy.delete();
		}
		// 对方也删除自己
		UserBuddy userBuddy2 = BuddyManager.getUserBuddy(buddyId, userId);
			if (userBuddy2 != null) {
			userBuddy2.delete();
		}

		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		ProtoDataUtils.updatePBUserData(pbUserData, userBuddyBlack, true);
		ProtoDataUtils.deletePBUserData(pbUserData, userBuddy);
		return response;
	}


	// CMD_GAME_BUDDY_APP_LIST = 71304;// 获取好友申请列表
	public static Object CMD_GAME_BUDDY_APP_LIST(RequestParam clientParam) throws Exception {
		CSGameBuddyAppListRequest request = CSGameBuddyAppListRequest.parseFrom(clientParam.getData());
		CSGameBuddyAppListResponse.Builder response = CSGameBuddyAppListResponse.newBuilder();
		long userId = clientParam.getUserId();
		List<UserBuddyApply> list = BuddyManager.getUserBuddyApplyList(userId);	// 获取好友申请列表
		List<Long> blackUserIdList = BuddyManager.getBlackUserIdList(userId);	// 获取好友申请列表
		List<UserBuddyApply> result = new ArrayList<>();
		for (Model model : list) {
			UserBuddyApply entity = (UserBuddyApply) model;
			// 若在黑名单中 删除申请信息
			if (blackUserIdList.contains(entity.getApplyId())) {
				entity.delete();
				continue;
			}
			result.add(entity);
		}
		Collections.sort(result, Comparator.comparing((UserBuddyApply o) -> o.getApplyTime()).reversed());
		for (UserBuddyApply userBuddyApply : list) {
			response.addList(userBuddyApply.takeBuilder());
		}
		return response;
	}


	// CMD_GAME_BUDDY_APP_ACCEPT = 71305;// 接受好友申请
	public static Object CMD_GAME_BUDDY_APP_ACCEPT(RequestParam clientParam) throws Exception {
		CSGameBuddyAppAcceptRequest request = CSGameBuddyAppAcceptRequest.parseFrom(clientParam.getData());	// 获取请求数据
		CSGameBuddyAppAcceptResponse.Builder response = CSGameBuddyAppAcceptResponse.newBuilder();
		long userId = clientParam.getUserId();
		long applyId = request.getApplyId();	// 获取申请者id
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		if(applyId == 0) {
			//一键同意
			List<UserBuddyApply> userBuddyApplyList = BuddyManager.getUserBuddyApplyList(userId);
			for (UserBuddyApply userBuddyApply : userBuddyApplyList) {
				long applyIdTmp = userBuddyApply.getApplyId();
				// 黑名单不能加好友
				UserBuddyBlack userBuddyBlack = BuddyManager.getUserBuddyBlack(userId, applyIdTmp);
				if (userBuddyBlack != null) {
					continue;
				}

				// 判断我的好友数量是否达到上限
				long count = BuddyManager.getUserBuddyCount(userId);
				if (count >= AllParam.BUDDY_ADD_MAX) {
					break;
				}

				// 判断对方好友数量是否达到上限
				long count2 = BuddyManager.getUserBuddyCount(applyIdTmp);
				if (count2 >= AllParam.BUDDY_ADD_MAX) {
					continue;
				}

				// 添加好友
				UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, applyIdTmp);
				if (userBuddy == null) {
					userBuddy = new UserBuddy(userId, applyIdTmp);
					userBuddy.doCreate();
				}

				UserBuddy userBuddy2 = BuddyManager.getUserBuddy(applyIdTmp,userId);
				if (userBuddy2 == null) {
					userBuddy2 = new UserBuddy(applyIdTmp, userId);
					userBuddy2.doCreate();
				}

				// 删除好友申请信息
				userBuddyApply.delete();
				// // 如果对方也同时申请 则同意后删除对方的申请
				UserBuddyApply userBuddyApp2 = BuddyManager.getUserBuddyApply(applyIdTmp, userId);
				if (userBuddyApp2 != null) {
					// 删除申请信息
					userBuddyApp2.delete();
				}
				ProtoDataUtils.updatePBUserData(pbUserData, userBuddy);
			}
		} else {
			if (applyId == userId) {
				return ErrorWord.MYSELF;
			}
			UserBuddyApply userBuddyApply = BuddyManager.getUserBuddyApply(userId, applyId);	// 获取好友申请信息
			if (userBuddyApply == null) {
				return ErrorWord.NOT_DATA;
			}

			// 黑名单不能加好友
			UserBuddyBlack userBuddyBlack = BuddyManager.getUserBuddyBlack(userId, applyId);
			if (userBuddyBlack != null) {
				return ErrorWord.WRONG_STATUS;
			}

			// 判断我的好友数量是否达到上限
			long count = BuddyManager.getUserBuddyCount(userId);
			if (count >= AllParam.BUDDY_ADD_MAX) {
				return ErrorWord.ALREADY_MAX;
			}

			// 判断对方好友数量是否达到上限
			long count2 = BuddyManager.getUserBuddyCount(applyId);
			if (count2 >= AllParam.BUDDY_ADD_MAX) {
				return ErrorWord.NOT_DATA_10;
			}

			// 添加好友
			UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, applyId);
			if (userBuddy == null) {
				userBuddy = new UserBuddy(userId, applyId);
				userBuddy.doCreate();
			}

			UserBuddy userBuddy2 = BuddyManager.getUserBuddy(applyId,userId);
			if (userBuddy2 == null) {
				userBuddy2 = new UserBuddy(applyId, userId);
				userBuddy2.doCreate();
			}

			// 删除好友申请信息
			userBuddyApply.delete();
			// // 如果对方也同时申请 则同意后删除对方的申请
			UserBuddyApply userBuddyApp2 = BuddyManager.getUserBuddyApply(applyId, userId);
			if (userBuddyApp2 != null) {
				// 删除申请信息
				userBuddyApp2.delete();
			}
			ProtoDataUtils.updatePBUserData(pbUserData, userBuddy);
			//		// 通知添加好友
//		CSGameBuddyChangeNoticeResponse.Builder builder = CSGameBuddyChangeNoticeResponse.newBuilder();
//		builder.setAddUserBuddy(userBuddy2.takeBuilder());
//		JsonObject obj = BaseHandler.getResponseOk(CmdEnum.EnumCmdID.CMD_GAME_BUDDY_CHANGE_NOTICE_VALUE,
//				builder.build().toByteArray());
//		GameManager.pushToUsers(appid, obj);
		}
		return response;
	}

	// CMD_GAME_BUDDY_APP_REFUSE = 71306;// 拒绝好友申请
	public static Object CMD_GAME_BUDDY_APP_REFUSE(RequestParam clientParam) throws Exception {
		CSGameBuddyAppRefuseRequest request = CSGameBuddyAppRefuseRequest.parseFrom(clientParam.getData());
		CSGameBuddyAppRefuseResponse.Builder response = CSGameBuddyAppRefuseResponse.newBuilder();
		long userId = clientParam.getUserId();
		long appId = request.getBuddyId();
		if (appId == 0) {
			//一键拒绝
			List<UserBuddyApply> list = BuddyManager.getUserBuddyApplyList(userId);	// 获取好友申请列表
			for (UserBuddyApply userBuddyApply : list) {
				// 删除好友申请信息
				userBuddyApply.delete();
			}
		} else {
			UserBuddyApply userBuddyApply = BuddyManager.getUserBuddyApply(userId, appId);	// 获取好友申请信息
			if (userBuddyApply == null) {
				return ErrorWord.NOT_DATA;
			}
			// 删除好友申请信息
			userBuddyApply.delete();
		}
		response.setBuddyId(appId);
		return response;
	}

	// CMD_GAME_BUDDY_BLACK_LIST = 71307;// 获取好友黑名单列表
	public static Object CMD_GAME_BUDDY_BLACK_LIST(RequestParam clientParam) throws Exception {
		CSGameBuddyBlackListRequest request = CSGameBuddyBlackListRequest.parseFrom(clientParam.getData());
		CSGameBuddyBlackListResponse.Builder response = CSGameBuddyBlackListResponse.newBuilder();
		long userId = clientParam.getUserId();
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		List<UserBuddyBlack> list = BuddyManager.getUserBuddyBlackList(userId);	// 获取黑名单列表
		for (UserBuddyBlack userBuddyBlack : list) {
			ProtoDataUtils.updatePBUserData(pbUserData, userBuddyBlack, true);
		}
		return response;
	}

	//  CMD_GAME_BUDDY_BLACK_DEL = 71308;// 删除黑名单
	public static Object CMD_GAME_BUDDY_BLACK_DEL(RequestParam clientParam) throws Exception {
		CSGameBuddyBlackDelRequest request = CSGameBuddyBlackDelRequest.parseFrom(clientParam.getData());
		CSGameBuddyBlackDelResponse.Builder response = CSGameBuddyBlackDelResponse.newBuilder();
		long userId = clientParam.getUserId();
		long blackId = request.getBlackId();
		UserBuddyBlack userBuddyBlack = BuddyManager.getUserBuddyBlack(userId,blackId);
		if (userBuddyBlack == null) {
			return ErrorWord.NOT_DATA;
		}
		userBuddyBlack.delete();
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		ProtoDataUtils.deletePBUserData(pbUserData, userBuddyBlack);
		return response;
	}


	//  CMD_GAME_BUDDY_FIND = 71309;// 查询玩家列表
	public static Object CMD_GAME_BUDDY_FIND(RequestParam clientParam) throws Exception {
		CSGameBuddyFindRequest request = CSGameBuddyFindRequest.parseFrom(clientParam.getData());
		CSGameBuddyFindResponse.Builder response = CSGameBuddyFindResponse.newBuilder();
		long userId = clientParam.getUserId();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		// 功能未开启
		String searchUserName = request.getKeyword();// 查询名称
		// 过滤敏感字符
		if (SensitivewordEngine.isContaintSensitiveWord(searchUserName, SensitivewordEngine.MinMatchType)) {
			return ErrorWord.BAD_WORD;
		}
		String key2 = Tool.dropFourByte(searchUserName);
		if (!key2.equalsIgnoreCase(searchUserName)) {
			return ErrorWord.CHAR_NOT_ALLOW;
		}
		String sql;
		JsonArray params = new JsonArray();
		// 如果为14位纯数字 则为ID搜索
		long searchUserId = 0;
		try {
			searchUserId = Long.parseLong(searchUserName, 16);
		} catch (Exception e) {
//			throw new IllegalArgumentException("Invalid invite code format: " + inviteCode, e);
		}
		if (searchUserId != 0) {
			sql = "select id,user_name from user_info where id = ? limit 1;";
			params.add(searchUserId);
		} else {
			sql = "select id,user_name from user_info where user_name like ? limit " + AllParam.BUDDY_FIND_NUM_MAX + ";";
			params.add(searchUserName + "%");
		}
		JsonArray jsonArray = Future.await( MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params));
		for (int i = 0; i < jsonArray.size(); i++) {
			JsonObject jsonObject = jsonArray.getJsonObject(i);
			long uid = jsonObject.getLong("id");
			// 排除自己
			if (uid == userId) {
				continue;
			}
			String name = jsonObject.getString("user_name");
			if (name.isEmpty()) {
				continue;
			}
			if (SensitivewordEngine.isContaintSensitiveWord(name, SensitivewordEngine.MinMatchType)) {
				continue;
			}
			response.addList(BuddyManager.takeBuddyBuilder(null,0,uid));
		}
		return response;
	}


	// CMD_GAME_BUDDY_ADD = 71310;// 申请加好友
	public static Object CMD_GAME_BUDDY_ADD(RequestParam clientParam) throws Exception {
		CSGameBuddyAddRequest request = CSGameBuddyAddRequest.parseFrom(clientParam.getData());
		CSGameBuddyAddResponse.Builder response = CSGameBuddyAddResponse.newBuilder();
		long userId = clientParam.getUserId();
		long applyId = request.getApplyId();// 添加好友ID
		if (applyId == userId) {
			return ErrorWord.MYSELF;
		}

		if (GameUser.getUserInfo(applyId) == null){
			return ErrorWord.INVALID_OPERATION;
		}
		UserInfo userInfo = GameUser.getUserInfo(userId);
		UserBuddyApplyInfo applyUserBuddyApplyInfo = BuddyManager.getUserBuddyApplyInfo(applyId);
		//判断是否满足申请条件
		if (applyUserBuddyApplyInfo.getIsLimlit() == 1) {
			//进行好友申请判断
			if(userInfo.getVip() < applyUserBuddyApplyInfo.getLimitVip()) {
				return ErrorWord.WRONG_STATUS;
			}
			if (userInfo.getLevel() < applyUserBuddyApplyInfo.getLimitLevel()) {
				return ErrorWord.WRONG_STATUS;
			}
			if (applyUserBuddyApplyInfo.getLimitUnion() == 1) {
				UserUnion userUnion = UnionManager.getUserUnion(userId);
				UserUnion userUnionApply = UnionManager.getUserUnion(applyId);
				if (userUnionApply.getUnionId() == 0  || (userUnion.getUnionId() != userUnionApply.getUnionId())) {
					return ErrorWord.WRONG_STATUS;
				}
			}
		}
		// 判断申请的对象是否存在黑名单中
		UserBuddyBlack userBuddyBlack = BuddyManager.getUserBuddyBlack(userId, applyId);
		if (userBuddyBlack != null) {
			return ErrorWord.NOT_DATA_1;
		}
		// 判断是否是好友
		UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, applyId);
		if (userBuddy != null) {
			return ErrorWord.REPEATED_OPERATION;
		}

		// 判断被申请人好友列表是否已满
		if (BuddyManager.getUserBuddyApplyCount(applyId) >= AllParam.BUDDY_APPLY_MAX) {
			return ErrorWord.NOT_DATA;
		}
		// 判断我是否在对方的黑名单中
		UserBuddyBlack userBuddyBlack2 = BuddyManager.getUserBuddyBlack(applyId, userId);
		if (userBuddyBlack2 == null) {
			// 如果没有申请记录，则添加一条申请记录
			UserBuddyApply userBuddyapply = BuddyManager.getUserBuddyApply(applyId, userId);
			if (userBuddyapply == null) {
				userBuddyapply = new UserBuddyApply(applyId, userId);
				userBuddyapply.doCreate();
			} else {
				// 已经申请过
				return ErrorWord.ALREADY_MAX;
			}
			// 推送申请红点
			UserInfo applyUserInfo = GameUser.getUserInfo(applyId);
			UserExtInfo applyUserExtInfo = GameUser.getUserExtInfo(applyId);
			GameUser.sendRedPointPrompt(applyUserInfo, applyUserExtInfo, SystemConstant.RED_POINT_BUDDY_APPLY);

		}
		return response;
	}

	// CMD_GAME_BUDDY_SEND_GIFT = 71311;// 赠送礼物
	public static Object CMD_GAME_BUDDY_SEND_GIFT(RequestParam clientParam) throws Exception {
		CSGameBuddySendGiftRequest request = CSGameBuddySendGiftRequest.parseFrom(clientParam.getData());
		CSGameBuddySendGiftResponse.Builder response = CSGameBuddySendGiftResponse.newBuilder();
		long userId = clientParam.getUserId();
		long buddyId = request.getBuddyId();// 好友ID
		// 计算还有多少赠送次数
		UserAffair userAffair = GameUser.getUserAffair(userId);
		int remainGiftNum = AllParam.BUDDY_GIVE_MAX - userAffair.getBuddyGiftNum();
		if (remainGiftNum <= 0) {
			return ErrorWord.TIMES_LACK;
		}
		UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, buddyId);
		if (userBuddy == null) {
			return ErrorWord.CLIENT_REFRESH;
		}
		if (TimeUtils.isToday(userBuddy.getGiftTime())) {
			return ErrorWord.ALREADY_MAX;
		}
		// 更新赠送信息
		userBuddy.putGiftTime(TimeUtils.getCurTime());
		userBuddy.update();
		// 更新好友获赠信息
		UserBuddy userBuddyInfo = BuddyManager.getUserBuddy(userBuddy.getBuddyId(), userId);
		if (userBuddyInfo != null && userBuddyInfo.getGiftStatus() == GameConstant.GIFT_STATUS_NULL) {
			userBuddyInfo.putGiftStatus(GameConstant.GIFT_STATUS_UNGET);
			userBuddyInfo.putReceiveGiftTime(TimeUtils.getCurTime());
			userBuddyInfo.update();
		}
		// 更新赠送次数信息
		userAffair.addBuddyGiftNum(1);
		userAffair.update();
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		ProtoDataUtils.updatePBUserData(pbUserData, userAffair);
		ProtoDataUtils.updatePBUserData(pbUserData, userBuddy);
		return response;
	}

	// CMD_GAME_BUDDY_GET_GIFT = 71312;// 领取礼物
	public static Object CMD_GAME_BUDDY_GET_GIFT(RequestParam clientParam) throws Exception {
		CSGameBuddyGetGiftRequest request = CSGameBuddyGetGiftRequest.parseFrom(clientParam.getData());
		CSGameBuddyGetGiftResponse.Builder response = CSGameBuddyGetGiftResponse.newBuilder();
		long userId = clientParam.getUserId();
		long buddyId = request.getBuddyId();// 好友ID
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();

		UserBuddy userBuddy = BuddyManager.getUserBuddy(userId, buddyId);
		if (userBuddy == null) {
			return ErrorWord.CLIENT_REFRESH;
		}
		if (userBuddy.getGiftStatus() != GameConstant.GIFT_STATUS_UNGET) {
			return ErrorWord.WRONG_STATUS;
		}

		UserAffair userAffair = GameUser.getUserAffair(userId);
		if (userAffair.getBuddyGetGiftNum() >= AllParam.BUDDY_GET_MAX) {
			return ErrorWord.ALREADY_MAX;
		}
		// 更新领取信息
		userBuddy.putGiftStatus(GameConstant.GIFT_STATUS_GET);
		userBuddy.update();
		userAffair.addBuddyGetGiftNum(1);
		userAffair.update();

		UserInfo userInfo = GameUser.getUserInfo(userId);
		for (int i = 0; i < AllParam.BUDDY_PRE_GIFT.length; i += 2) {
			RewardManager.addReward(userInfo, AllParam.BUDDY_PRE_GIFT[i], AllParam.BUDDY_PRE_GIFT[i + 1], pbUserData, LogType.BUDDY_GIFT);// 获得相应奖励
		}
		ProtoDataUtils.updatePBUserData(pbUserData, userAffair);
		ProtoDataUtils.updatePBUserData(pbUserData, userBuddy);
		return response;
	}

	// CMD_GAME_BUDDY_RECOMMEND = 72821;// 系统推荐好友
	public static Object CMD_GAME_BUDDY_RECOMMEND(RequestParam clientParam) throws Exception {
		CSGameBuddyRecommendRequest request = CSGameBuddyRecommendRequest.parseFrom(clientParam.getData());
		CSGameBuddyRecommendResponse.Builder response = CSGameBuddyRecommendResponse.newBuilder();
		long userId = clientParam.getUserId();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		// 功能未开启
		if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_BUDDY)) {
			return ErrorWord.MODULE_LOCKED;
		}
		if (userInfo == null) {
			return ErrorWord.NOT_DATA;// 玩家数据不存在
		}
		// 系统推荐好友 功能
		List<Long> buddyUserIdList = BuddyManager.getBuddyUserIdList(userId);// 当前用户的好友ID
		List<Long> blackUserIdList = BuddyManager.getBlackUserIdList(userId);// 当前用户的黑名单ID
		List<Long> resultList = new ArrayList<>();
		if (AllParam.BUDDY_RECOMMEND_IS_OPEN == 0 && AllParam.BUDDY_RECOMMEND_PARAMS != null
				&& AllParam.BUDDY_RECOMMEND_PARAMS.length >= 2 && AllParam.BUDDY_RECOMMEND_PARAMS.length % 2 == 0) {
//			// 查战力排行榜 方案算法
//			int myRank = RankManager.getMyRank(RankManager.SERVER_RANK_POWER, userId, userInfo.getServerId());
//			for (int i = 0; i < AllParam.BUDDY_RECOMMEND_PARAMS.length; i+=2) {
//				// 最多查询5次 防止死循环
//				if (i >= 10) {
//					break;
//				}
//				int diffRank = AllParam.BUDDY_RECOMMEND_PARAMS[i];// 战力排行榜差距名次
//				int loginTime = AllParam.BUDDY_RECOMMEND_PARAMS[i + 1];// 最近X天登陆
//				int startRank = myRank - diffRank >= 0 ? myRank - diffRank : 0;
//				int endRank = myRank + diffRank;
//
//				JsonArray powerRankArray = RankManager.getRankListByIndex(RankManager.SERVER_RANK_POWER,
//						startRank, endRank, false, userInfo.getServerId());
//				addToRecommendListRank(userId, powerRankArray, buddyUserIdList, blackUserIdList, resultList, loginTime);
//				if (resultList.size() >= AllParam.BUDDY_RECOMMEND_LIST) {
//					break;
//				}
//			}
//			if (resultList.size() == 0) {
//				JsonArray powerRankArray = RankManager.getRankListByIndex(RankManager.SERVER_RANK_POWER,
//						0, 100, false, userInfo.getServerId());
//				addToRecommendListRank(userId, powerRankArray, buddyUserIdList, blackUserIdList, resultList, 5);
//			}
		} else {
			// 查数据库 方案算法
			for (int i = 0; i < AllParam.BUDDY_FIND_LV.length; i++) {
				if (resultList.size() < AllParam.BUDDY_RECOMMEND_LIST) {
					long time = System.currentTimeMillis();
					JsonArray params2 = new JsonArray();
					String sql2 = "SELECT id,user_name FROM user_info where server_id = ? and login_time > ? and level >= ? and level <= ? \n" +
							"order by login_time desc limit 300;";
					params2.add(userInfo.getServerId());
					params2.add(TimeUtils.getCurTime() - AllParam.BUDDY_FIND_SIGN[i] * TimeUtils.DAY);
					params2.add(userInfo.getLevel() - AllParam.BUDDY_FIND_LV[i] > 0 ? userInfo.getLevel() - AllParam.BUDDY_FIND_LV[i] : 0);
					params2.add(userInfo.getLevel() + AllParam.BUDDY_FIND_LV[i]);

					JsonArray jsonArray2 = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql2, params2));
					BuddyManager.addToRecommendList(userId, jsonArray2, buddyUserIdList, blackUserIdList, resultList);
				} else {
					break;
				}
			}
		}
		// 返回结果列表
		for (long uid : resultList) {
			response.addList(BuddyManager.takeBuddyBuilder(null,0,uid));
		}
		return response;
	}

	//CMD_GAME_BUDDY_APPLY_LIMIT = 71314;// 申请好友条件设置
	public static Object CMD_GAME_BUDDY_APPLY_LIMIT(RequestParam clientParam) throws Exception {
		CSGameBuddyApplyLimitRequest request = CSGameBuddyApplyLimitRequest.parseFrom(clientParam.getData());
		CSGameBuddyApplyLimitResponse.Builder response = CSGameBuddyApplyLimitResponse.newBuilder();
		long userId = clientParam.getUserId();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		// 功能未开启
		if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_BUDDY)) {
			return ErrorWord.MODULE_LOCKED;
		}
		if (userInfo == null) {
			return ErrorWord.NOT_DATA;// 玩家数据不存在
		}
		int isLimit = request.getIsLimit();
		int limitLevel = request.getLimitLevel();
		int limitVip = request.getLimitVip();
		int limitUnion = request.getLimitUnion();

		if (!Tool.isInList(AllParam.FRIEND_LEVEL_LIMIT,limitLevel)) {
			return ErrorWord.BAD_PARAM;
		}

		if (!Tool.isInList(AllParam.FRIEND_VIP_LIMIT,limitVip)) {
			return ErrorWord.BAD_PARAM;
		}

		UserBuddyApplyInfo userBuddyApplyInfo = BuddyManager.getUserBuddyApplyInfo(userId);
		userBuddyApplyInfo.putLimitLevel(limitLevel);
		userBuddyApplyInfo.putLimitVip(limitVip);
		userBuddyApplyInfo.putLimitUnion((byte) limitUnion);
		userBuddyApplyInfo.putIsLimlit((byte) isLimit);
		userBuddyApplyInfo.update();
		
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();
		ProtoDataUtils.updatePBUserData(pbUserData, userBuddyApplyInfo);

		return response;
	}

	//CMD_GAME_BUDDY_SEND_GET_GIFT = 71315;// 一键领取并赠送礼物
	public static Object CMD_GAME_BUDDY_SEND_GET_GIFT(RequestParam clientParam) throws Exception {
		CSGameBuddySendGetGiftRequest request = CSGameBuddySendGetGiftRequest.parseFrom(clientParam.getData());
		CSGameBuddySendGetGiftResponse.Builder response = CSGameBuddySendGetGiftResponse.newBuilder();
		long userId = clientParam.getUserId();
		UserInfo userInfo = GameUser.getUserInfo(userId);
		// 功能未开启
		if (!SystemManager.checkModuleOpen(userInfo, SystemConstant.SYSTEM_MODULE_ID_BUDDY)) {
			return ErrorWord.MODULE_LOCKED;
		}
		UserAffair userAffair = GameUser.getUserAffair(userId);
		List<UserBuddy> list = BuddyManager.getUserBuddyList(userId);
		Common.PBUserData.Builder pbUserData = response.getUserBuilder();

		int getGiftNum = AllParam.BUDDY_GET_MAX - userAffair.getBuddyGetGiftNum();//计算可领取次数
		int remainGiftNum = AllParam.BUDDY_GIVE_MAX - userAffair.getBuddyGiftNum();//计算可赠送次数
		int getCount = 0;
		int remainConut = 0;
		for (UserBuddy userBuddy : list) {
			boolean isUpdate = false;

			//领取
			if(getGiftNum > getCount && userBuddy.getGiftStatus() == GameConstant.GIFT_STATUS_UNGET) {
				// 更新领取信息
				userBuddy.putGiftStatus(GameConstant.GIFT_STATUS_GET);
				for (int i = 0; i < AllParam.BUDDY_PRE_GIFT.length; i += 2) {
					RewardManager.addReward(userInfo, AllParam.BUDDY_PRE_GIFT[i], AllParam.BUDDY_PRE_GIFT[i + 1], pbUserData, LogType.BUDDY_GIFT);// 获得相应奖励
				}
				getCount++;
				isUpdate = true;
			}

			//赠送
			if (remainGiftNum > remainConut && !TimeUtils.isToday(userBuddy.getGiftTime())) {
				// 更新赠送信息
				userBuddy.putGiftTime(TimeUtils.getCurTime());
				// 更新好友获赠信息
				UserBuddy userBuddyInfo = BuddyManager.getUserBuddy(userBuddy.getBuddyId(), userId);
				if (userBuddyInfo != null && userBuddyInfo.getGiftStatus() == GameConstant.GIFT_STATUS_NULL) {
					userBuddyInfo.putGiftStatus(GameConstant.GIFT_STATUS_UNGET);
					userBuddyInfo.putReceiveGiftTime(TimeUtils.getCurTime());
					userBuddyInfo.update();
				}
				remainConut++;
				isUpdate = true;
			}

			if (isUpdate) {
				userBuddy.update();
				ProtoDataUtils.updatePBUserData(pbUserData, userBuddy);
			}

			//如果无领取次数和无赠送次数,跳出循环
			if (getGiftNum <= getCount && remainGiftNum <= remainConut) {
				break;
			}
		}

		if(getCount > 0) {
			// 更新领取次数信息
			userAffair.addBuddyGetGiftNum(getCount);
			userAffair.update();
		}

		if(remainConut > 0) {
			// 更新赠送次数信息
			userAffair.addBuddyGiftNum(remainConut);
			userAffair.update();
		}

		ProtoDataUtils.updatePBUserData(pbUserData, userAffair);
		return response;
	}
}
